package com.cyzy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyzy.Utils.TokenUtils;
import com.cyzy.domain.MessageBean;
import com.cyzy.domain.TUser;
import com.cyzy.dto.ResponseData;
import com.cyzy.Utils.Md5;
import com.cyzy.mapper.TUserMapper;
import com.cyzy.service.TUserService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 10204
 * @description 针对表【t_user(用户表，用于存储用户信息)】的数据库操作Service实现
 * @createDate 2024-11-12 14:32:29
 */
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements TUserService {
    @Autowired
    private TUserMapper tUserMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public ResponseData login(String phone, String password) {
//        // 获取验证码UUID
//        String uuid = tUser.getUuid();
//        System.out.println("------------uuid是：" + uuid);
//        // 从Redis获取验证码
//        String captcha = redisTemplate.opsForValue().get(uuid);
//        System.out.println("------------captcha222是：" + captcha);
//        // 校验验证码
//        if (captcha == null || "".equals(captcha) || !tUser.getCaptcha().toLowerCase().equals(captcha.toLowerCase())) {
//            return ResponseData.no2("验证码错误");
//        }
//        // 使用MD5加密用户密码
//        Md5 md5 = new Md5();
//        String encryptedPassword = md5.md5(tUser.getUserPassword());
//        // 使用手机号查询用户
//        QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("user_phone", tUser.getUserPhone()); // 使用用户手机号查询
//        TUser user = tUserMapper.selectOne(queryWrapper);
//        if (user == null) {
//            return ResponseData.no2("用户不存在");
//        }
//        // 校验密码
//        if (user.getUserPassword().equals(encryptedPassword)) {
//            // 生成Token并存入Redis
//            String token = TokenUtils.creatToken(tUser.getUuid());
//            redisTemplate.opsForValue().set(token, tUser.getUuid(), 30, TimeUnit.MINUTES);  // 设置token的过期时间为30分钟
//            // 返回登录成功的响应
//            return ResponseData.ok2("登录成功");
//        } else {
//            throw new RuntimeException("用户名或密码错误");

        String code = redisTemplate.opsForValue().get(phone);
        if (code == null || code == "") {
            return ResponseData.ok2("false1");
        } else {
            if (password.equals(code)) {
                QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("user_phone", phone); // 使用用户手机号查询
                TUser user = tUserMapper.selectOne(queryWrapper);
                if (user == null) {
                    TUser tUser = new TUser();
                    tUser.setUserPhone(phone);
                    tUser.setUserState("0");
                    tUserMapper.insert(tUser);
                    String user1 = tUser.toString();
                    String token = TokenUtils.creatToken(user1);
                    redisTemplate.opsForValue().set(token, token, 30, TimeUnit.MINUTES);  // 设置token的过期时间为30分钟
                    return ResponseData.ok2(token);
                } else {
                    String user1 = user.toString();
                    String token = TokenUtils.creatToken(user1);
                    List <String> list=new ArrayList<>();
                    list.add(user.getUserId().toString());
                    list.add(token);
                    redisTemplate.opsForValue().set(token, token, 30, TimeUnit.MINUTES);  // 设置token的过期时间为30分钟
                    return ResponseData.ok2(list);
                }
            } else {
                return ResponseData.ok2("false");
            }
        }
//        }
    }

    @Override
    public ResponseData UUIDLogin(String phone, String password, String uuid, String code) {
        String code1 = redisTemplate.opsForValue().get(uuid);
        if (code == null || code == "") {
            return new ResponseData(0, "false1", null, 0);
        } else {
            if (code.equals(code1)) {
                QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("user_phone", phone); // 使用用户手机号查询
                TUser user = tUserMapper.selectOne(queryWrapper);
                if (user == null) {
                    return new ResponseData(0, "false3", null, 0);
                } else {
                    if (user.getUserPassword() == "" || user.getUserPassword() == null) {
                        return new ResponseData(0, "false4", null, 0);
                    } else {
                        if (user.getUserPassword().equals(password)) {
                            List<String> list=new ArrayList<>();
                            list.add(user.getUserId().toString());

                            String token = TokenUtils.creatToken(user.toString());
                            list.add(token);
                            redisTemplate.opsForValue().set(token, token, 30, TimeUnit.MINUTES);  // 设置token的过期时间为30分钟
                            return new ResponseData(0, "success", list, 0);
                        } else {
                            return new ResponseData(0, "false5", null, 0);
                        }
                    }
                }
            } else {
                return new ResponseData(0, "false2", null, 0);
            }
        }
    }

    @Override
    public ResponseData register(TUser tUser) {
        // 检查是否已存在相同的手机号
        QueryWrapper<TUser> queryWrapperPhone = new QueryWrapper<>();
        queryWrapperPhone.eq("user_phone", tUser.getUserPhone());
        if (tUserMapper.selectCount(queryWrapperPhone) > 0) {
            return ResponseData.no2("手机号已存在");
        }

        // 检查是否已存在相同的身份证号
        QueryWrapper<TUser> queryWrapperIdcard = new QueryWrapper<>();
        queryWrapperIdcard.eq("user_idcard", tUser.getUserIdcard());
        if (tUserMapper.selectCount(queryWrapperIdcard) > 0) {
            return ResponseData.no2("身份证号已存在");
        }

        // 检查是否已存在相同的邮箱
        QueryWrapper<TUser> queryWrapperemail = new QueryWrapper<>();
        queryWrapperemail.eq("user_email", tUser.getUserEmail());
        if (tUserMapper.selectCount(queryWrapperemail) > 0) {
            return ResponseData.no2("邮箱已存在");
        }

        tUser.setUserState("0");
        // 保存用户信息到数据库
        int result = tUserMapper.insert(tUser);
        // 根据插入结果返回相应的提示信息
        if (result > 0) {
            return ResponseData.ok2("注册成功");
        } else {
            return ResponseData.no2("注册失败");
        }
    }

    @Override
    public ResponseData updatePassword(String phone, String password, String code) {
        String code1 = redisTemplate.opsForValue().get(phone);
        if (code1 == "" || code1 == null) {
            return new ResponseData(0, "false", null, 0);
        } else {
            if (code1.equals(code)) {
                QueryWrapper<TUser> queryWrapperIdcard = new QueryWrapper<>();
                queryWrapperIdcard.eq("user_phone", phone);
                TUser tUser = new TUser();
                tUser.setUserPhone(phone);
                tUser.setUserPassword(password);
                int re = tUserMapper.update(tUser, queryWrapperIdcard);
                if (re == 0) {
                    return new ResponseData(0, "false2", null, 0);
                } else {

                    return new ResponseData(0, "success", null, 0);
                }
            } else {
                return new ResponseData(0, "false1", null, 0);
            }
        }
    }

    @Override
    public ResponseData emailLogin(String email, String emailCode) {
        // 检查是否已存在相同的邮箱
        QueryWrapper<TUser> queryWrapperemail = new QueryWrapper<>();
        queryWrapperemail.eq("user_email", email);
        TUser tUser = tUserMapper.selectOne(queryWrapperemail);
        if (tUser == null) {
            return new ResponseData(0, "false", null, 0);
        } else {
            String code = redisTemplate.opsForValue().get(email);
            if (code == null || code == "") {
                return new ResponseData(0, "false1", null, 0);
            } else {
                if (emailCode.equals(code)) {
                    String token = TokenUtils.creatToken(tUser.toString());
                    redisTemplate.opsForValue().set(token, token, 30, TimeUnit.MINUTES);
                    return new ResponseData(0, "success", null, 0);
                } else {
                    return new ResponseData(0, "false2", null, 0);
                }
            }
        }
    }

    //    查询用户信息
    @Override
    public ResponseData getUser(TUser tUser) {
        QueryWrapper<TUser> queryWrapperIdcard = new QueryWrapper<>();
        queryWrapperIdcard.eq("user_id", tUser.getUserId());
        TUser tUser1 = tUserMapper.selectOne(queryWrapperIdcard);
        if (tUser1 == null) {
            return new ResponseData(0, "false", null, 0);
        }
        return new ResponseData(0, "success", tUser1, 0);
    }

    // 修改用户密码
    @Override
    public ResponseData setpassword(Integer userId, String oldpassword, String newpassword) {
        QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        TUser tUser = tUserMapper.selectOne(queryWrapper);
        if (tUser.equals(null) || (tUser.equals(""))) {
            return new ResponseData(300, "false", "用户不存在或登录失效", 0);
        } else {
            if (tUser.getUserPassword().equals(oldpassword)) {
                tUser.setUserPassword(newpassword);
                int re = tUserMapper.updateById(tUser);
                if (re > 0) {
                    return ResponseData.ok();
                }
            }
        }
        return new ResponseData(300, "false", "密码修改失败", 0);
    }

    //修改用户信息
    @Override
    public int setUser(TUser tUser) {
        return tUserMapper.updateById(tUser);
    }

    @Override
    public ResponseData updateEditlnfoUser(String phone, String code, String oldPassword, String newPassword) {
       if (oldPassword.equals(newPassword)) {
           String code1 = redisTemplate.opsForValue().get(phone);
           if (code1==null|| code1=="" ){
               return new ResponseData(0, "false3", null, 0);
           }else {
               if (code1.equals(code)) {
                   QueryWrapper<TUser> queryWrapperIdcard = new QueryWrapper<>();
                   queryWrapperIdcard.eq("user_phone", phone);
                   TUser tUser = new TUser();
                   tUser.setUserPhone(phone);
                   tUser.setUserPassword(newPassword);
                   int re=tUserMapper.update(tUser,queryWrapperIdcard);
                   if (re==0){
                       return new ResponseData(0, "false2", null, 0);
                   }else {
                       return new ResponseData(0, "success", null, 0);
                   }
               }else {
                   return new ResponseData(0, "false1", null, 0);
               }
           }

       }else {
           return new ResponseData(0, "false", null, 0);
       }
    }

    @Override
    public ResponseData svaeMessage(@NotNull MessageBean messageBean) {
        messageBean.setStatus("未读");
        int re=tUserMapper.saveMessage(messageBean);
        if (re == 0) {
            return new ResponseData(0, "false", null, 0);
        }else {
            return new ResponseData(0, "success", null, 0);
        }
    }
}






